package cn.myeasyai.service;

import cn.myeasyai.config.FileConfig;
import cn.myeasyai.dto.ImageDTO;
import cn.myeasyai.feature.FeatureExtractor;
import cn.myeasyai.image.ImageSearcher;
import cn.myeasyai.milvus.VectorService;
import cn.myeasyai.util.IdWorker;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author fushoujiang
 */
@Service
public class ImageService {
    @Resource
    private IdWorker idWorker;

    @Resource
    private UploadFileService uploadFileService;
    @Resource
    private VectorService vectorService;
    @Resource
    private FeatureExtractor featureExtractor;
    @Resource
    private ImageSearcher imageSearcher;


    @Resource
    private FileConfig fileConfig;

    public ImageDTO imageInit(MultipartFile multipartFile, ImageDTO imageDTO) {
        try (InputStream inputStream = multipartFile.getInputStream()) {
            return imageInit(inputStream, imageDTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public ImageDTO imageInit(InputStream inputStream, ImageDTO imageDTO) {
        insertModel(inputStream, imageDTO);
        return imageDTO;

    }

    public List<ImageDTO> searchModel(InputStream inputStream,Integer topK) {
        try {
            final List<Float> floats = featureExtractor.extractFeatures(inputStream);
            final List<ImageDTO> result = imageSearcher.search(floats,topK);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw  new RuntimeException("系统处理失败");

    }


    private void insertModel(final InputStream inputStream, ImageDTO imageDTO) {
        try {
            final byte[] bytes = inputStream.readAllBytes();
            final List<Float> floats = featureExtractor.extractFeatures(new ByteArrayInputStream(bytes));
            final String url = uploadFileService.uploadFile(new ByteArrayInputStream(bytes), imageDTO.getFileName());
            imageDTO.setUrl(url);
            vectorService.initImageVector(imageDTO, floats);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
